
package com.dhcc.bpm.modules.orga.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.dhcc.bpm.common.json.JSONObject;
import com.dhcc.bpm.common.utils.DateUtils;
import com.dhcc.bpm.modules.common.vo.SelectVo;
import com.dhcc.bpm.modules.orga.entity.Orga;
import com.dhcc.bpm.modules.orga.mapper.OrgaMapper;
import com.dhcc.bpm.modules.orga.service.IOrgaService;
import com.dhcc.bpm.modules.orga.vo.*;
import com.dhcc.bpm.modules.system.service.ISerialNumberService;
import com.dhcc.bpm.modules.workflow.dto.ProcessStartDto;
import lombok.AllArgsConstructor;
import lombok.NoArgsConstructor;
import org.springblade.core.mp.base.BaseServiceImpl;
import org.springblade.core.tool.api.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @ClassName OrgaServiceImpl
 * @Description 机构信息表 服务实现类
 * @Author daina
 * @Date 2020/2/24 19:25
 * @Version V1.0
 * @Copyright: 2020 东华软件 . All rights reserved.
 */
@Service("opc_orga")
@AllArgsConstructor
@NoArgsConstructor
public class OrgaServiceImpl extends BaseServiceImpl<OrgaMapper, Orga> implements IOrgaService {

    @Autowired
    private OrgaMapper orgaMapper;
    @Autowired
    ISerialNumberService serialNumberService;
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    //    @Autowired
//    private IWorkFlowService iWorkFlowService;
    @Value("${workflow.base-url}")
    String workflow_base_url;
    @Autowired
    RestTemplate restTemplate;

    @Override
    public IPage<OrgaVO> selectOrgaPage(IPage<OrgaVO> page, OrgaVO orga) {
        return page.setRecords(baseMapper.selectOrgaPage(page, orga));
    }

    @Override
    public IPage<OrgaVO> selectControllerOrga(IPage<OrgaVO> page, OrgaVO orga) {
        return page.setRecords(baseMapper.selectControllerOrga(page, orga));
    }

    @Override
    public IPage<OrgaVO> selectUnControllerOrgaList(IPage<OrgaVO> page, OrgaVO orga) {
        return page.setRecords(baseMapper.selectUnControllerOrgaList(page, orga));
    }

    @Override
    public IPage<OrgaVO> UnControllerOrgaGateList(IPage<OrgaVO> page, OrgaVO orga) {
        return page.setRecords(baseMapper.UnControllerOrgaGateList(page, orga));
    }

    @Override
    public List<OrgaVO> selectOrgaByProductId(Long opcProductId) {
        return baseMapper.selectOrgaByProductId(opcProductId);
    }

    @Override
    public IPage<OrgaVO> apiList(IPage<OrgaVO> page, OrgaVO orga) {
        return page.setRecords(orgaMapper.apiList(page, orga));
    }

    @Override
    public IPage<OrgaVO> changeList(IPage<OrgaVO> page, OrgaVO orga) {
        return page.setRecords(orgaMapper.changeList(page, orga));
    }

    @Override
    public OrgaInfoVo selectOrgaInfo(Long id) {
        return baseMapper.selectOrgaInfo(id);
    }

    @Override
    public OrgaManVo selectMan(Long id) {
        return baseMapper.selectMan(id);
    }

    @Override
    public OrgaOtherManVo selectOtherMan(Long id) {
        return baseMapper.selectOtherMan(id);
    }

    /**
     * @param id
     * @return com.dhcc.bpm.modules.orga.vo.OrgaInfoNewVo
     * @Description 查询变更后机构信息
     * @Author sjm
     * @Date 9:15 2020/2/27 0027
     **/
    @Override
    public OrgaInfoNewVo selectOrgaInfoNew(Long id) {
        return baseMapper.selectOrgaInfoNew(id);
    }

    /**
     * @param id
     * @return com.dhcc.bpm.modules.orga.vo.OrgaManNewVo
     * @Description 查询变更后注册联系人
     * @Author sjm
     * @Date 9:18 2020/2/27 0027
     **/
    @Override
    public OrgaManNewVo selectManNew(Long id) {
        return baseMapper.selectManNew(id);
    }

    /**
     * @param id
     * @return com.dhcc.bpm.modules.orga.vo.OrgaOtherManNewVo
     * @Description 查询变更后其他注册联系人
     * @Author sjm
     * @Date 9:20 2020/2/27 0027
     **/
    @Override
    public OrgaOtherManNewVo selectOtherManNew(Long id) {
        return baseMapper.selectOtherManNew(id);
    }

    @Override
    public OrgaTestVo selectOrgaTest(Long id) {
        return baseMapper.selectOrgaTest(id);
    }

    /**
     * @param
     * @return int
     * @Description TODO
     * @Author Mdd
     * @Date 2020/3/20 11:43
     **/
    @Override
    public int countOrga() {
        return baseMapper.countOrga();
    }

    /**
     * @param parentId
     * @return int
     * @throws
     * @Description 机构变更未审核数量
     * @Author xiafayu
     * @Date 2020/4/10 15:35
     **/
    @Override
    public int changeNum(Long parentId) {
        return baseMapper.changeNum(parentId);
    }

    @Override
    public Orga findOrgaByUserId(Long opcUserId) {
        return baseMapper.findOrgaByUserId(opcUserId);
    }

    @Override
    public Orga findOrgaByDeptId(String deptId) {
        return baseMapper.findOrgaByDeptId(deptId);
    }

    @Override
    public List<SelectVo> selectByOrgaName() {
        return baseMapper.selectByOrgaName();
    }

    @Override
    public boolean deleteIdAndParentId(List<Long> ids) {
        return baseMapper.deleteIdAndParentId(ids);
    }

    @Override
    public List<Orga> findByPId(String pid) {
        return baseMapper.findByPId(pid);
    }

    @Override
    public OrgaVO selectDetail(Orga orga) {
        return orgaMapper.selectDetail(orga);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public R addOrga(Orga opcOrga) {
        //机构注册
        String orgaCode = serialNumberService.generateSerialNumberByModelCode("opc_orga_code");
        opcOrga.setOrgaCard(orgaCode);
        opcOrga.setRegTime(DateUtils.getNowDate());
        opcOrga.setAccessTime(DateUtils.getNowDate());
        opcOrga.setCreateTime(DateUtils.getNowDate());
        opcOrga.setOrgaStatus("1");
        if (opcOrga.getStatus() == null || opcOrga.getStatus() != 1) {
            opcOrga.setStatus(0);
        }
        opcOrga.setIsDeleted(0);
        opcOrga.setExpSeq(stringRedisTemplate.opsForValue().get("expSeq"));
        orgaMapper.insert(opcOrga);

        //发起工作流审批
        ProcessStartDto processStartDto = new ProcessStartDto();
        processStartDto.setAppId("i" + opcOrga.getId());
        processStartDto.setUserId(String.valueOf(opcOrga.getOpcUserId()));
        processStartDto.setProcessKey("org_accreditation");
        Map<String, Object> wfParm = new HashMap<>();
        wfParm.put("params", "1234");
        processStartDto.setWfParm(wfParm);
        // 调用发布流程接口
        JSONObject resJson = null;
        try {
            resJson = restTemplate.postForObject(workflow_base_url + "/api/workflow/processinstance/start", processStartDto, JSONObject.class);
        } catch (Exception e) {
            log.error("执行审批任务异常：{}", e);
            return R.fail("执行审批任务异常！");
        }
        // 发布流程成功
        if (resJson != null && resJson.getInt("code") == 200) {
            return R.success("机构创建成功，正在审核中！");
        }

        //回滚渠道信息和测试环境信息
        TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();

        return R.fail("机构创建失败！");
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public R updateOrga(Orga opcOrga) {
        //机构修改
        opcOrga.setAuthFlag("0");
        opcOrga.setOperationType("2");
        opcOrga.setStatus(1);
        Orga oldOrga = orgaMapper.selectById(opcOrga.getParentId());
        opcOrga.setOrgaName(oldOrga.getOrgaName());
        opcOrga.setOrgaShort(oldOrga.getOrgaShort());
        opcOrga.setCreditCode(oldOrga.getCreditCode());
        opcOrga.setOrgaCode(oldOrga.getOrgaCode());
        opcOrga.setOrgaCard(oldOrga.getOrgaCard());
        opcOrga.setIataNum(oldOrga.getIataNum());
        opcOrga.setIsDomestic(oldOrga.getIsDomestic());
        opcOrga.setRegTime(DateUtils.getNowDate());
        opcOrga.setAccessTime(DateUtils.getNowDate());
        opcOrga.setCreateTime(DateUtils.getNowDate());
        opcOrga.setOrgaStatus("1");
        if(opcOrga.getStatus() == null || opcOrga.getStatus() != 1){
            opcOrga.setStatus(0);
        }
        opcOrga.setIsDeleted(0);
        opcOrga.setExpSeq(stringRedisTemplate.opsForValue().get("expSeq"));
       orgaMapper.insert(opcOrga);

        //发起工作流审批
        ProcessStartDto processStartDto = new ProcessStartDto();
        processStartDto.setAppId("k" + opcOrga.getId());
        processStartDto.setUserId(String.valueOf(opcOrga.getOpcUserId()));
        processStartDto.setProcessKey("org_accreditation_change");
        Map<String, Object> wfParm = new HashMap<>();
        wfParm.put("params", "1234");
        processStartDto.setWfParm(wfParm);
        // 调用发布流程接口
        JSONObject resJson = null;
        try {
            resJson = restTemplate.postForObject(workflow_base_url + "/api/workflow/processinstance/start", processStartDto, JSONObject.class);
        } catch (Exception e) {
            log.error("执行审批任务异常：{}", e);
            return R.fail("执行审批任务异常！");
        }
        // 发布流程成功
        if (resJson != null && resJson.getInt("code") == 200) {
            return R.success("机构变更成功，正在审核中！");
        }

        //回滚渠道信息和测试环境信息
        TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();

        return R.fail("机构变更失败！");
    }

}
